package public

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true // 允许跨域（小程序本地调试用）
	},
}

/**
 * websocket连接
 */
func WsHandler(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println("WebSocket Upgrade Error:", err)
		return
	}
	defer conn.Close()

	for {
		// 读取消息
		mt, message, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("ReadMessage Error:", err)
			break
		}
		fmt.Printf("收到消息：%s\n", message)

		// 回复消息（原样返回）
		err = conn.WriteMessage(mt, message)
		if err != nil {
			fmt.Println("WriteMessage Error:", err)
			break
		}
	}
}
